
<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 初始数据
const initialData = {
  componentName: 'inputData', // 新增组件名称字段
  url: {
    urlfore: 'http://127.0.0.1:5000',
    urlafter: '/api/submit-form'
  },
  data: [
    {
      type: 'text',
      label: '',
      name: '',
      placeholder: ''
    }
  ]
}

// 响应式数据
const formData = reactive(JSON.parse(JSON.stringify(initialData)))
const previewData = ref('')

// 添加新字段
const addField = () => {
  formData.data.push({
    type: 'text',
    label: '',
    name: '',
    placeholder: ''
  })
}

// 删除字段
const removeField = (index) => {
  if (formData.data.length > 1) {
    formData.data.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一个字段')
  }
}

// 生成输出
const generateOutput = () => {
  // 验证数据
  if (!formData.componentName || formData.componentName.trim() === '') {
    ElMessage.error('请输入组件名称')
    return
  }

  if (!formData.url.urlfore || !formData.url.urlafter) {
    ElMessage.error('请填写完整的URL配置')
    return
  }

  for (let i = 0; i < formData.data.length; i++) {
    const field = formData.data[i]
    if (!field.type || !field.label || !field.name) {
      ElMessage.error(`请填写第 ${i + 1} 个字段的完整信息`)
      return
    }

    // 验证类型
    if (!['text', 'textarea', 'file'].includes(field.type)) {
      ElMessage.error(`第 ${i + 1} 个字段的类型只能是 text、textarea 或 file`)
      return
    }
  }

  // 处理数据：移除空的 placeholder，设置默认值
  const processedData = {
    [formData.componentName]: {
      url: {
        urlfore: formData.url.urlfore,
        urlafter: formData.url.urlafter
      },
      data: formData.data.map(item => {
        const processedItem = {
          type: item.type,
          label: item.label,
          name: item.name
        }

        // 只有当 placeholder 有值时才添加该属性
        if (item.placeholder && item.placeholder.trim() !== '') {
          processedItem.placeholder = item.placeholder
        }

        return processedItem
      })
    }
  }

  // 转换为 JSON 字符串
  const outputString = JSON.stringify(processedData, null, 0)
  previewData.value = outputString

  // 打印到控制台
  console.log('生成的配置:')
  console.log(outputString)

  // 显示成功消息
  ElMessage.success('配置已生成并打印到控制台')
}

// 复制到剪贴板
const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(previewData.value)
    ElMessage.success('配置已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, JSON.parse(JSON.stringify(initialData)))
  previewData.value = ''
  ElMessage.info('表单已重置')
}
const getpreviewData=()=>{
  return previewData.value
}

const deleteUserConfig=async () => {
  const loading = ref(false)

  const formData2 = reactive({
    treedata: '',// 注意：这里是小写，和后端一致
    userconfiger: ""
  })
  formData2.userconfiger=formData.componentName
  try {
    loading.value = true

    // 直接构造 FormData 对象
    const formDataToSend = new FormData()
    formDataToSend.append('userconfiger',formData2.userconfiger) // 如果是对象需要转成字符串

    // 发送 POST 请求 - 使用表单格式
    const response = await fetch('http://127.0.0.1:5000/api/remove_user_configer_by_key', {
      method: 'POST',
      body: formDataToSend // 不需要设置 Content-Type，浏览器会自动设置
    })
    ElMessage.success('删除'+formData2.userconfiger+"成功！")

  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(`提交失败: ${error.message}`)
  } finally {
    loading.value = false
  }

}

defineExpose({
  getpreviewData
})
</script>

<template>
  <div class="input-data-configurator">
    <el-form :model="formData" >
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 组件名称配置 -->
          <el-divider content-position="left">组件配置</el-divider>
          <el-form-item label="组件名称" required>
            <el-input
                v-model="formData.componentName"
                placeholder="请输入组件名称，如：inputData、formConfig、userForm等"
                style="max-width: 300px;"
            />
          </el-form-item>

          <!-- URL 配置部分 -->
          <el-divider content-position="left">URL 配置</el-divider>
          <el-form-item label="URL 前缀">
            <el-input v-model="formData.url.urlfore" placeholder="请输入URL前缀，如：http://127.0.0.1:5000" />
          </el-form-item>
          <el-form-item label="URL 后缀">
            <el-input v-model="formData.url.urlafter" placeholder="请输入URL后缀，如：/api/submit-form" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- Data 配置部分 -->
          <el-divider content-position="left">表单字段配置</el-divider>

          <div v-for="(item, index) in formData.data" :key="index" class="data-item">
            <el-card class="field-card">
              <template #header>
                <div class="card-header">
                  <span>字段 {{ index + 1 }}</span>
                  <el-button type="danger" size="small" @click="removeField(index)">删除</el-button>
                </div>
              </template>

              <el-form-item label="字段类型" required>
                <el-select v-model="item.type" placeholder="请选择字段类型">
                  <el-option label="文本输入" value="text" />
                  <el-option label="文本区域" value="textarea" />
                  <el-option label="文件上传" value="file" />
                </el-select>
              </el-form-item>

              <el-form-item label="标签提示" required>
                <el-input v-model="item.label" placeholder="自己看到的描述提示" />
              </el-form-item>

              <el-form-item label="字段名称" required>
                <el-input v-model="item.name" placeholder="后端接受时的key" />
              </el-form-item>

              <el-form-item label="提示文本">
                <el-input v-model="item.placeholder" placeholder="提示文本placeholder" />
              </el-form-item>
            </el-card>
          </div>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="addField">添加字段</el-button>
        <el-button type="success" @click="generateOutput">生成配置</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="danger" @click="deleteUserConfig">删除该name的配置</el-button>
      </div>

      <!-- 预览区域 -->
      <el-divider content-position="left">配置预览</el-divider>
      <el-alert
          v-if="previewData"
          :title="`组件名称: ${formData.componentName}`"
          type="info"
          :closable="false"
          style="margin-bottom: 16px;"
      />
      <el-card v-if="previewData">
        <template #header>
          <div class="preview-header">
            <span>生成的 JSON 配置(请点击此按钮后再点击确认)</span>
            <el-button type="primary" text @click="copyToClipboard">复制</el-button>
          </div>
        </template>
        <pre class="json-preview">{{ previewData }}</pre>
      </el-card>
    </el-form>
  </div>
</template>


<style scoped>
.input-data-configurator {
  max-width: 800px;
  margin: 20px auto;
}

.data-item {
  margin-bottom: 16px;
}

.field-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
  margin-bottom: 24px;
}

.json-preview {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}
</style>